<template>
  <div>
    <!-- 三级分类 -->
    <Category :scene="scene" />
    <el-card style="margin-top: 10px">
      <div v-show="scene === 0">
        <el-button v-has="'btn.Attr.add'" :disabled="categoryStore.c3Id === ''" type="primary" size="default" icon="Plus" @click="addAttr">添加平台属性</el-button>
        <el-table style="margin-top: 10px" border stripe :data="attrArr">
          <el-table-column label="序号" type="index" align="center" width="80px" />
          <el-table-column label="属性名称" width="120px" prop="attrName" />
          <el-table-column label="属性值名称">
            <template #default="{ row }">
              <el-tag v-for="(item, _index) in row.attrValueList" :key="item.id" style="margin-right: 10px">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #default="{ row }">
              <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)" />
              <el-popconfirm v-has="'btn.Attr.remove'" :title="`你确认要删除${row.attrName}`" width="200px" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button v-has="'btn.Attr.update'" type="primary" size="small" icon="Delete" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene === 1">
        <el-form ref="form" :model="attrParams" :inline="true">
          <el-form-item label="属性名称" prop="attrName">
            <el-input v-model="attrParams.attrName" placeholder="请输入属性名称" />
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="Plus" @click="addAtttrValue">添加属性值</el-button>
        <el-button @click="cancel">取消</el-button>
        <el-table border stripe style="margin-top: 10px" :data="attrParams.attrValueList">
          <el-table-column label="序号" type="index" align="center" />
          <el-table-column label="属性值" width="col.width">
            <template #default="{ row, $index }">
              <el-input v-if="row.flag" :ref="(vc: any) => (inputArr[$index] = vc)" v-model="row.valueName" placeholder="请你输入属性值名称" size="normal" clearable @blur="toLook(row, $index)" />
              <span v-else @click="toEdit($index)">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="col.width">
            <template #default="{ $index }">
              <el-button type="danger" size="small" icon="Delete" @click="attrParams.attrValueList.splice($index, 1)" />
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 10px">
          <el-button type="primary" :disabled="attrParams.attrValueList.length > 0 ? false : true" @click="save">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import useCategoryStore from '@/store/modules/category';
import { nextTick, onBeforeUnmount, reactive, ref, watch } from 'vue';

import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr/index';
import type { AttrResponseData, AttrList, Attr, AttrValue } from '@/api/product/attr/type';
import { ElMessage } from 'element-plus';

let categoryStore = useCategoryStore();

// 监听select中c3选项的值，一旦发生变动立刻请求属性与属性值
watch(
  () => categoryStore.c3Id,
  () => {
    attrArr.value = [];
    if (!categoryStore.c3Id) return;
    getAttr();
  },
);

//存储属性与属性值
let attrArr = ref<AttrList>([]);

//获取已有属性和属性值的方法
const getAttr = async () => {
  let result: AttrResponseData = await reqAttr(categoryStore.c1Id, categoryStore.c2Id, categoryStore.c3Id);
  if (result.code === 200) {
    attrArr.value = result.data;
  }
};

//定义卡片切换变量
let scene = ref<number>(0); //0:表格|1:表单

//添加平台属性切换
const addAttr = () => {
  scene.value = 1;
  //获取c3id
  //清空表单
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,
  });
};

//修改平台属性切换
const updateAttr = (row: Attr) => {
  scene.value = 1;

  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
};

//取消添加|修改属性
const cancel = () => {
  scene.value = 0;
  // getAttr();
};

//收集新增的属性的数据
const attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
});

//添加属性值按钮的回调
const addAtttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, // 控制每个属性是编辑还是查看
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

// 节流阀
let loading = ref<boolean>(false);

// 保存添加|修改属性值
const save = async () => {
  if (loading.value) return;
  loading.value = true;
  let result: any = await reqAddOrUpdateAttr(attrParams);
  if (result.code === 200) {
    scene.value = 0;
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    });
    getAttr();
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    });
  }
  loading.value = false;
};

//属性名称编辑模式转查看模式
let toLook = (row: AttrValue, $index: number) => {
  if (row.valueName.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    });
    return;
  }

  let repeat = attrParams.attrValueList.find((item) => {
    if (item != row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    });
    return;
  }
  attrParams.attrValueList[$index].flag = false;
};

//属性名称查看模式转编辑式
let toEdit = ($index: number) => {
  attrParams.attrValueList[$index].flag = true;
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};

// 属性值el-input组件实例数组
let inputArr = ref<any>([]);

// 删除属性与属性值
let deleteAttr = async (attrId: number) => {
  let result: any = await reqRemoveAttr(attrId);
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    });
  }
};

// 卸载组件时，清除pinia中存的分类值
onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style lang="scss" scoped></style>
